% This function computes the variance decomposition of x in a FAVAR model
% 
% Syntax:
% 
% [r2com,vardecxcom] = vardecx(x,F,lam,Fmat,smat,horizon,shock)
% 
% where the inputs are:      
%   x:  matrix with series for variance decomposition
%   F:  matrix with common components series
%   lam: estimated parameters in the observation equation
%   Fmat: companion matrix
%   smat: Cholesky factorization matrix
%   horizon: horizon for the variance computation
%   shock: vector with the shocks
%
% and the outputs are:
%   r2com: variance decomposition in common factors and specific shocks   
%   vardecxcom: variance decomposition of the common factors shocks
%
%Jean Boivin, Marc Giannoni, Ilian Mihov

function [r2com,vardecxcom]=vardecx(x,F,lam,Fmat,smat,horizon,shock);


varx=var(x);
com=F*lam;          %common component in the observable equation


% computes the variance in the VAR equation
varf=vardec(Fmat,smat,horizon,shock);     % variance due to monetary shock
varftot=vardec(Fmat,smat,horizon,ones(size(smat,1),1));  % total variance

% varf(end,end)/varftot(end,end)
% stop

% computes the variance in the observation equation
vardecx=lam'*varf*lam;          % variance in x's due to monetary shock
vardecxtot=lam'*varftot*lam;    % variance in x's due to all commom factors                


% [diag(vardecx) diag(vardecxtot)]

vardecxcom=diag(vardecx)./diag(vardecxtot);
r2com=(var(com)./varx)';